package models

import (
	"time"

	"github.com/go-xorm/xorm"
)

type MonitorHeartTemp struct {
	//DStart    time.Time `xorm:"dStart datetime('2016-01-02 00:00:00')"`
	DStart    time.Time `xorm:"dStart"`
	NEnters   int       `xorm:"nEnters"`
	NExits    int       `xorm:"nExits"`
	NPassings int       `xorm:"nPassings"`
	NReturns  int       `xorm:"nReturns"`
	SDev      string    `xorm:"sDev"`
}

func (MonitorHeartTemp) TableName() string {
	return "MonitorHeart_temp"
}

// TODO insert into monitor_heart_temp
func MonitorHeartTempInsert(db *xorm.Engine, dStart time.Time, nEnters int, nExits int, nPassings int, nReturns int, sDev string) error {
	_, err := db.Exec("INSERT INTO MonitorHeart_temp (dStart, nEnters, nExits, nPassings, nReturns, sDev) VALUES (@p1, @p2, @p3, @p4, @p5)", dStart, nEnters, nExits, nPassings, nReturns, sDev)
	if err != nil {
		loggerl.Errorf("插入数据时出错：%v", err)
		return err
	}
	return nil
}

// TODO update monitor_heart_temp use dStart
func MonitorHeartTempUpdate(db *xorm.Engine, dStart time.Time, nEnters int, nExits int, sDev string) error {
	_, err := db.Exec("UPDATE MonitorHeart_temp SET nEnters = ?, nExits = ? WHERE dStart = ? and sDev = ?", nEnters, nExits, dStart, sDev)
	if err != nil {
		loggerl.Errorf("更新数据时出错：%v", err)
		return err
	}
	return nil
}

func GetMonitorHeartTemp(db *xorm.Engine, dStart time.Time) (*MonitorHeartTemp, error) {
	// 查询
	monitorHeartTemp := &MonitorHeartTemp{}
	_, err := db.Where("dStart = ?", dStart).Get(monitorHeartTemp)
	if err != nil {
		loggerl.Errorf("查询时出错：%v", err)
		return nil, err
	}
	return monitorHeartTemp, nil
}

// TODO 根据dStart字段判断是否存在，存在就更新调用MonitorHeartTempUpdate。不存在就插入MonitorHeartTempInsert
func MonitorHeartTempUpdateOrInsert(db *xorm.Engine, dStart time.Time, nEnters int, nExits int, sDev string) error {
	query := "SELECT count(1) FROM MonitorHeart_temp WHERE dStart = @p1"

	results, err := db.Query(query, dStart)
	if err != nil {
		loggerl.Errorf("查询时出错：%v", err)
		return err
	}

	if len(results) > 0 {
		// 记录存在，更新数据
		loggerl.Debugf("MonitorHeartTempUpdateOrInsert 更新数据 dStart: %v, nEnters: %d, nExits: %d, sDev: %s", dStart, nEnters, nExits, sDev)
		return MonitorHeartTempUpdate(db, dStart, nEnters, nExits, sDev)
	} else {
		// 记录不存在，插入数据
		loggerl.Debugf("MonitorHeartTempUpdateOrInsert 插入数据 dStart: %v, nEnters: %d, nExits: %d, sDev: %s", dStart, nEnters, nExits, sDev)
		return MonitorHeartTempInsert(db, dStart, nEnters, nExits, 0, 0, sDev)
	}
}
